import db from './db'
import Mock from 'mockjs'
import jwt from 'jsonwebtoken'
import { parseUrl, pick } from '../utlis'

// 读取当前用户信息
Mock.mock('product/info', 'get', () => {
  let info = {}

  try {
    const token = localStorage.getItem('Oppo-token')
    //
    info = jwt.decode(token, '3210')
  } catch (err) {
    console.log(err)
  }
  const result = db.select('Oppo_product', item => {
    return item.username === info.data
  }).map(item =>
    pick(item, ['id', 'stock','summary','price', 'state'])
  )
  return {
    err: 0,
    desc: '执行成功',
    result
  }
})
// 添加
Mock.mock('product/add', 'post', ({ body }) => {
  const {  pid,title, summary='',price, picurl,stock, content='',state=1 } = JSON.parse(body)

  db.add('Oppo_product', { pid,title, summary,price, picurl,stock, content,state })
  return { err: 0, desc: '执行成功' }
})

// 修改
Mock.mock('product/edit', 'post', ({ body }) => {
    const {id, pid,title, summary='',price, picurl,stock, content='',state=1 } = JSON.parse(body)

    db.put('Oppo_product',id, { pid,title, summary,price, picurl,stock, content,state })
    return { err: 0, desc: '执行成功' }
})
// 审核
Mock.mock('product/state', 'post', ({ body }) => {
  const { id, state } = JSON.parse(body)
  db.put('Oppo_product', id, { state })

  return { err: 0, desc: '执行成功' }
})
// 查找
Mock.mock(/product\/list(\?.+)?/, 'get', ({ url }) => {
  // 分页
  let { state, pid,price,keyword = '', page = 1, pagesize = 3 } = parseUrl(url)
  state = +state
  price = price ? price.split('-') : false
  keyword = decodeURIComponent(keyword)
  page = +page
  pagesize = +pagesize

  const searchResult = db.select('Oppo_product', item => {
    return (item.state === state || !state) && 
            (item.pid === +pid || !pid) && 
            (item.price >= price[0] && item.price <= price[1] || !price) &&
            (item.title.includes(keyword) || !keyword)
  })
  
  const total = searchResult.length
  const totalpage = Math.ceil(total / pagesize)
  if (page > totalpage) page = totalpage
  const start = (page - 1) * pagesize
  const end = start + pagesize

  const pageResult = searchResult.slice(start, end)
  return { err: 0, result: pageResult, page, total, pagesize, totalpage, desc: '执行成功' }
})
// 删除
Mock.mock('product/del', 'post', ({ body }) => {
  const { ids } = JSON.parse(body)
  db.delete('Oppo_product', ids)
  return {
    err: 0,
    desc: '执行成功'
  }
})
